package com.cnswhy.cloud.common.redis.service;

import com.cnswhy.cloud.common.core.utils.SystemClockUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import static com.cnswhy.cloud.common.redis.constant.RedisConstant.GEN_COMMON_ID;

public class IdGeneratorService {
    @Autowired
    RedisService redisService;

    public Long genCommonId() {
        return generatorId(GEN_COMMON_ID);
    }
    public String genCommonIdString() {
        return genCommonId().toString();
    }

    public Long generatorId(String biz) {
        // 转成数字类型，可排序
        return incrOrderId(biz, getOrderPrefix(SystemClockUtil.getDate()));
    }


    private String getOrderPrefix(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int year = c.get(Calendar.YEAR);
        int day = c.get(Calendar.DAY_OF_YEAR);
        int hour =  c.get(Calendar.HOUR_OF_DAY);
        String dayFmt = String.format("%1$03d", day);
        String hourFmt = String.format("%1$02d", hour);
        StringBuffer prefix = new StringBuffer();
        prefix.append((year - 2000)).append(dayFmt).append(hourFmt);
        return prefix.toString();
    }

    /**
     * @Description 支持一个小时100w个订单号的生成
     *
     * @author butterfly
     * @param prefix
     * @return
     */
    private Long incrOrderId(String biz, String prefix) {
        String orderId = null;
        String key = "cnswhy:#{biz}:id:".replace("#{biz}", biz).concat(prefix);
        try {
            Long index = redisService.incr(key,1L);
            String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date(SystemClockUtil.millisClock().now()));
            orderId = prefix.concat(time.substring(10,14)).concat(String.format("%1$06d", index));
        } catch(Exception ex) {
            System.out.println("分布式订单号生成失败异常。。。。。");
        }
        if (orderId == null || orderId.isEmpty()){
            return null;
        }
        return Long.parseLong(orderId);
    }
}
